import java.util.concurrent.TimeUnit;
/**
 * 死锁示例
 */
public class Thread18 {
    public static void main(String[] args) {
        Object lockA=new Object();
        Object lockB=new Object();

        Thread t1=new Thread(()->{
            //1.占有一把锁(锁A)
            synchronized (lockA) {
                System.out.println("线程1：获得锁A");
                //让对方线程2先得到锁B，休眠1s
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //2.获取另一线程的锁
                synchronized (lockB){
                    System.out.println("线程1：获得锁B");
                }

            }
        });
        t1.start();

        Thread t2=new Thread(()->{
            //1.占有一把锁(锁B)
            synchronized (lockB) {
                System.out.println("线程2：获得了锁B");
                //休眠1s(保证线程1能有充足的时间得到锁A)
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //2.获取线程1的锁A
                synchronized (lockA){
                    System.out.println("线程2: 获得了锁A");
                }
            }
        });
        t2.start();
    }
}
